package org.jeecg.modules.htxincailiao.crawler.processor;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.htxincailiao.news.entity.HTNewsCategory;
import org.jeecg.modules.htxincailiao.news.service.IHTNewsCategoryService;
import org.jeecg.modules.htxincailiao.news.service.IHTNewsService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.ConsolePipeline;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author code4crafter@gmail.com <br>
 */
@Slf4j
@Component
public class OfWeekPageProcessor implements PageProcessor {
    @Value(value = "${jeecg.path.upload}")
    private String uploadPath;
//    public static final String URL_LIST = "http://www.xincailiao.com/news/news_list.aspx?fenlei=latest";

    //    https://xincailiao.ofweek.com/CATList-180400-8100-xincailiao.html
    public static final String URL_LIST = "https://xincailiao.ofweek.com/CAT-180422-inorganic.html";
    private static final String targetSite = "维科网•新材料（xincailiao.ofweek.com）";

    @Resource
    private IHTNewsService newsService;

    @Resource
    private IHTNewsCategoryService newsCategoryService;


    private Site site = Site
            .me()
            .setDomain(targetSite)
            .setSleepTime(3000)
            .setUserAgent(
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");


    @Override
    public void process(Page page) {
        //列表页
        if (page.getRequest().getUrl().equals(URL_LIST)) {
            String liSrcXPath = "//div[@class='article-con']/div[@class='article-item']/html()";

            List<String> liList = page.getHtml().xpath(liSrcXPath).all();
            for (String liString : liList) {
                Html liHtml = new Html(liString);
//                log.info("\n\nliHtml : {}\n\n", liHtml );

                String href = liHtml.xpath("//a/@href").get();
                log.info("\n\nhref : {}\n\n", href );
                String cover = liHtml.xpath("//a/img/@src").get();
//                String subname = liHtml.xpath("//div[@class='detail']/h2/a/text()").get();

                Map<String, Object> extras = new HashMap<>();
                if (oConvertUtils.isNotEmpty(cover)) {
                    extras.put("cover", cover);
                }

//                if (oConvertUtils.isNotEmpty(subname)) {
//                    extras.put("subname", subname);
//                }
//
                if(oConvertUtils.isNotEmpty(href)) {
                    Request request = new Request();
                    request.setMethod("get");
                    request.setUrl(href);
                    request.setExtras(extras);

                    page.addTargetRequest(request);
                }

            }

            //文章页(详情页)
        } else {

            Html pageHtml = page.getHtml();
            String name = pageHtml.xpath("//div[@class='artical']/p[@class='title']/text()").get();
            if (newsService.getByName(name) != null) {
                // 如果存在则直接结束
                return;
            }
            String subname = "";
//            String time = pageHtml.xpath("//div[@class='artical']/div[@class='artical-relative clearfix']/div[@class='time fl']/text()").get();
            String content = pageHtml.xpath("//div[@id='articleC' and @class='artical-content']/html()").get();

            Html contentHtml = new Html(content);

            // 提取新闻内容中所有img标签
            List<String> images = contentHtml.regex("\\<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>").all();
            Map<String, String> imagesMap = images.stream().collect(Collectors.toMap(s -> s, s -> s, (s1, s2) -> s2));

            // 保存到本地
            LocalFileUtils locals = new LocalFileUtils(uploadPath);
            for (Map.Entry<String, String> entity: imagesMap.entrySet()) {
                try {
                    String localPath = "/htxincailiao-api/" + locals.saveFileToLocal(entity.getKey(), "https://xincailiao.ofweek.com");
                    imagesMap.put(entity.getKey(), localPath);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 替换content中的内容
            for (Map.Entry<String, String> entity: imagesMap.entrySet()) {
                content = content.replace(entity.getKey(), entity.getValue());
            }

            String source = "维科网•新材料";
            String cover = "";

            Map<String, Object> extras = page.getRequest().getExtras();
            if (oConvertUtils.isNotEmpty(extras.get("cover"))) {
                cover = extras.get("cover").toString();
            }
            log.debug("\n\nname : {}\n\n", name );

            log.debug("\n\nnewsCategoryService : {}\n\n", newsCategoryService );

            if (oConvertUtils.isNotEmpty(newsCategoryService)) {
                List<HTNewsCategory> categoryList = newsCategoryService.findAll();
                log.info("categoryList : {}\n", categoryList );
                if (oConvertUtils.isNotEmpty(categoryList)) {
                    HTNewsCategory category = categoryList.get(0);
                    String categoryId = category.getId();

                    newsService.saveForCrawlerCollectBy(categoryId, name, subname, source, cover, targetSite, content);
                }
            }
        }

    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void create(OfWeekPageProcessor pageProcessor) {
        Spider.create(pageProcessor).addUrl(URL_LIST).run();
    }

//    public static void main(String[] args) {
//        Spider.create(new OfWeekPageProcessor())
//                .addUrl(URL_LIST)
//                .addPipeline(new ConsolePipeline())
//                .run();
//    }


//    public static void main(String[] args) {
//        ConfigurableApplicationContext application = SpringApplication.run(JeecgSystemApplication.class, args);
//        OfWeekPageProcessor pageProcessor =  new OfWeekPageProcessor();
//        pageProcessor.newsService = (IHTNewsService)application.getBean("HTNewsServiceImpl");
////
//        Spider.create(pageProcessor).addUrl(URL_LIST)
//                .run();
//    }
}
